package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.user.IMemberService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.UserVerifyRequest;
import com.mall.user.dto.UserVerifyResponse;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//向磊
@RestController
@RequestMapping("/user")
public class UserController {


    @Reference(timeout = 20000, retries = 0, check = false)
    IMemberService iMemberService;


    @GetMapping("/loginOut")//退出1
    public ResponseData logout(HttpServletRequest request, HttpServletResponse response) {
        // 从jwt中，用户信息在cookie中，把cookie销毁
//        Cookie cookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, null, "/", 0);
//        response.addCookie(cookie);
        String attribute = ((String) request.getAttribute(TokenIntercepter.USER_INFO_KEY));
        request.removeAttribute(TokenIntercepter.USER_INFO_KEY);
//        return new ResponseUtil<>().setData(null);
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("access_token".equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        return new ResponseUtil<>().setData(null);
    }


    /*
    @RequestMapping("/loginOut")//退出2
    public ResponseData loginOut(HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse){
        Cookie cookie =
                CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, "", "/", 0);
        httpServletResponse.addCookie(cookie);
        return new ResponseUtil().setData(null);
    }*/


    @GetMapping("verify")//激活
    @Anoymous
    public ResponseData verify(String uid, String username) {
        UserVerifyRequest userVerifyRequest = new UserVerifyRequest();
        userVerifyRequest.setUuid(uid);
        userVerifyRequest.setUserName(username);

        UserVerifyResponse userVerifyResponse = iMemberService.userVerify(userVerifyRequest);

        if (SysRetCodeConstants.SUCCESS.getCode().equals(userVerifyResponse.getCode())) {
            return new ResponseUtil().setData(null);
        }

        return new ResponseUtil().setErrorMsg(userVerifyResponse.getMsg());

    }


}
